package com.todoclipse.common;

import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class HttpRequest implements Request{
	private static final String TODOIST = "https://todoist.com/API";
	private Reader reader;
	public HttpRequest() {
		reader = new Reader();
	}

	@SuppressWarnings("unchecked")
	public JSONArray invoke(String method, KeyValue... queryParams) {
		try {
			StringBuilder url = new StringBuilder()
			.append(TODOIST).append("/").append(method);
			if(queryParams!=null){
				if(queryParams.length > 0){
					url.append("?").append(queryParams[0]);					
				}
				for (int i = 1; i < queryParams.length; i++) {
					url.append("&").append(queryParams[i]);
				}
			}

			String result = reader.readContent(url.toString());
			Object parse = new JSONParser().parse(result);
			if(parse instanceof JSONArray){
				return (JSONArray) parse;
			}else{
				JSONArray array = new JSONArray();
				array.add(parse);
				return array;
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}